# -*- coding: utf-8 -*-
__author__ = 'Paul'
import random
from zope import schema
from zope.formlib import form
from zope.interface import implements
from zope.component import getMultiAdapter
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import\
    ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Products.bpContents import _
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from Acquisition import aq_inner
from plone.memoize.compress import xhtml_compress
from Products.bpContents.articulo import IArticulo
from Products.bpContents.galeria import IGaleria
from Products.bpContents.evento import IEvento
from Products.bpContents.libro import ILibro
from zope.schema.interfaces import IVocabularyFactory

from zope.site.hooks import getSite
import unicodedata
from intereses_portlets import CanalesVocabularyFactory
from plone.app.vocabularies.catalog import SearchableTextSourceBinder
CanalesVocabularyFactory
from Products.ATContentTypes.interface import IATFolder, IATImage,\
    IATBTreeFolder, IATDocument
from collective.portlet.foldercontents.widget import FixedErrorMessageChoiceInputWidget
from zope.security import checkPermission

class ITocPortlet(IPortletDataProvider):

    documento = schema.Choice(
        title=_(u"Documento"),
        description=_(u"Elija una pagina de la cual mostrará el campo 'Cuerpo'."),
        required=True,
        source=SearchableTextSourceBinder(
                {'object_provides' : (IATDocument.__identifier__,IArticulo.__identifier__,ILibro.__identifier__)},
            default_query='path:'))

class Assignment(base.Assignment):
    implements(ITocPortlet)

    def __init__(self, documento=""):
        self.documento= documento

    @property
    def title(self):
        cadena="Toc del documento"
        return cadena


class Renderer(base.Renderer):
    render = ViewPageTemplateFile('tocportlet.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)

        context = aq_inner(self.context)
        self.portal_transforms = getToolByName(self.context, 'portal_transforms')
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        self.anonymous = portal_state.anonymous()
        self.portal_url = portal_state.portal_url()
        self.typesToShow = portal_state.friendly_types()
        self.portal = getMultiAdapter((self.context, self.request),name=u'plone_portal_state').portal()



    @property
    def available(self):
        """If this portlet has what to show"""
        return True

    def getCuerpo(self):
        """Devuelve un html con los subheadings del documento"""
        return self._data()

    def getTitulo(self):
        """Devuelve el tútilo del documento elegido"""
        titulo=self._getContainer(self.data.documento).Title()
        return titulo
    def getURL(self):
        """Devuelve la url del documento elegido"""
        url=self._getContainer(self.data.documento).absolute_url()
        return url

    def _data(self):
        """Auxiliar que realiza la extraccion de los textos.Busca H2 y H3"""
        from lxml import etree
        from lxml.html import fromstring, tostring

        docu=self._getContainer(self.data.documento)

        if docu.portal_type=="Products.bpContents.articulo":
            text = docu.cuerpo.raw
        else:
            text = docu.getText()

        data = self.portal_transforms.convertTo('text/html', text, mimetype='text/-x-web-intelligent')
        html = data.getData()
        parseado=etree.HTML(html)
        listaH2=parseado.xpath("//h2")
        listaH3=parseado.xpath("//h3")
        flag=0
        texts=[]
        actualObjet=dict()
        idSeccion=-1

        for element in parseado.iter("*"):
            if element.text!=None and element!="":
                if element.tag=="h2" and element.text!="" and element.text!=None:

                    actualObjet=dict()
                    idSeccion=idSeccion+1
                    tituloC=element.text.encode('utf8')
                    if tituloC!=None:
                        tituTree=tituloC
                    else:
                        tituTree=""

                    actualObjet["titulo"]=tituTree
                    actualObjet["ramas"]=[]
                    actualObjet["idSeccion"]=idSeccion
                    texts.append(actualObjet)

                elif element.tag=="h3" and element.text!="":
                    flag+=1
                    tituloCC=element.text.encode('latin1')
                    if tituloCC!=None:

                        tituSubTree=tituloCC
                        actualObjet["ramas"].append({"titulo":tituSubTree,"idSeccion":idSeccion,"flag":flag})



        return texts

    @memoize
    def _getContainer(self, path):
        if not path:
            return None

        if path.startswith('/'):
            path = path[1:]

        if not path:
            return None

        return aq_inner(self.portal).restrictedTraverse(path, default=None)

class AddForm(base.AddForm):

    label = _(u"Agregar portlet")
    description = _(u"Este portlet muestra el contenido del documento que elija.")

    def create(self, data):
        assignment = Assignment()
        form.applyChanges(assignment, self.form_fields, data)
        return assignment

    @property
    def form_fields(self):
        form_fields = form.Fields(ITocPortlet)
        form_fields['documento'].custom_widget = FixedErrorMessageChoiceInputWidget
        return form_fields

    def create(self, data):
        return Assignment(documento=data.get('documento',''))

class EditForm(base.EditForm):
    label = _(u"Editar el portlet")
    description = _(u"Este portlet muestra el contenido del documento que elija.")

    @property
    def form_fields(self):
        form_fields = form.Fields(ITocPortlet)
        form_fields['documento'].custom_widget = FixedErrorMessageChoiceInputWidget
        return form_fields